/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ActionForm.*;
import bean.*;
import Model.*;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author cpn02
 */
public class CartAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {



        if(request.getSession().getAttribute("customer")==null)
        {
            return mapping.findForward("fail");
        }
        CartForm cart = (CartForm)form;
        long IDpro = Long.parseLong(cart.getIDpro());
        boolean flag=true;
         ArrayList<CartBean> carts;
        if(request.getSession().getAttribute("carts")==null)
        {
           carts =  new ArrayList<CartBean>();
        }
        else
        {
            carts =  (ArrayList<CartBean>) request.getSession().getAttribute("carts"); 
        }

        flag = AddCart(IDpro,carts);
        request.getSession().setAttribute("carts", carts);
        if(flag==true)
        {
            return mapping.findForward("success");
        }
        else
            return mapping.findForward("overAmount");

    }
    private static boolean AddCart(long IDpro,ArrayList<CartBean> carts)
    {
        Iterator<CartBean> it = carts.iterator();
        CartBean cart;
        Product pro;
        while(it.hasNext())
        {
            cart=  it.next();
            pro = cart.getPro();
            if(pro.getIDpro()==IDpro)
            {
                if(pro.getAmount()>cart.getAmount())
                {
                    cart.setAmount(cart.getAmount()+1);
                    return true;
                }
                return false;
            }
        }
        
        pro = ProModel.getProByID(IDpro);
        if(pro.getAmount()>0)
        {
            cart = new CartBean();
            cart.setPro(pro);
            cart.setAmount(1);
            carts.add(cart);
            return true;
        }
        else
            return false;

    }

}
